package com.fy.fyspace.common.manager;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * AI任务队列管理器
 */
@Slf4j
@Component
public class AiTaskQueueManager {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private static final String AI_TASK_QUEUE_KEY = "ai:task:queue";
    private static final long TASK_EXPIRE_TIME = 30; // 任务过期时间（分钟）

    /**
     * 添加任务到队列
     *
     * @param taskId AI任务ID
     */
    public void addTask(String taskId) {
        try {
            redisTemplate.opsForSet().add(AI_TASK_QUEUE_KEY, taskId);
            log.info("添加AI任务到队列成功: taskId={}", taskId);
        } catch (Exception e) {
            log.error("添加AI任务到队列失败: taskId={}, error={}", taskId, e.getMessage());
        }
    }

    /**
     * 从队列中移除任务
     *
     * @param taskId AI任务ID
     */
    public void removeTask(String taskId) {
        try {
            redisTemplate.opsForSet().remove(AI_TASK_QUEUE_KEY, taskId);
            log.info("从队列中移除AI任务成功: taskId={}", taskId);
        } catch (Exception e) {
            log.error("从队列中移除AI任务失败: taskId={}, error={}", taskId, e.getMessage());
        }
    }

    /**
     * 获取所有待处理的任务
     *
     * @return 任务ID集合
     */
    public Set<Object> getAllTasks() {
        try {
            Set<Object> tasks = redisTemplate.opsForSet().members(AI_TASK_QUEUE_KEY);
            if (CollUtil.isEmpty(tasks)) {
                return null;
            }
            log.debug("获取待处理AI任务列表: count={}", tasks.size());
            return tasks;
        } catch (Exception e) {
            log.error("获取AI任务列表失败: error={}", e.getMessage());
            return null;
        }
    }

    /**
     * 清空任务队列
     */
    public void clearQueue() {
        try {
            redisTemplate.delete(AI_TASK_QUEUE_KEY);
            log.info("清空AI任务队列成功");
        } catch (Exception e) {
            log.error("清空AI任务队列失败: error={}", e.getMessage());
        }
    }
} 